#
# Copyright 2012 ibiblio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import seedbank.messaging.log_helper as log_helper
from seedbank.messaging.libtorrent_status import TorrentStatusPrinter
from seedbank.mixin.tick_counter import TickCounterMixin

class TorrentManager(TickCounterMixin):
    def __init__(self, **kwargs):
        TickCounterMixin.__init__(self, **kwargs)
        self._verbose = kwargs.get('verbose', False)
        self._label = kwargs.get('label', '')
        self._log = log_helper.get_logger(self.__class__.__name__)

        if self._verbose:
            self._printer = TorrentStatusPrinter('server')
        else:
            self._printer = None

        # torrent timeout values
        self._inactive_torrent_timeout = kwargs.get('inactive_torrent_timeout', 60)

    def _tick(self, **kwargs):
        """
        Called from TickCounterMixin::tick

        :Parameters:
            - `session`: :class: libtorrent.session
        """
        try:
            session = kwargs.get('session', None)
            self._check_torrents(session)
        except Exception, e:
            self._log.error(str(e))

    def _check_torrents(self, session):
        torrents = session.get_torrents()
        for torrent in torrents:
            if self._printer:
                self._printer.print_single(torrent)
            self._check_torrent(session, torrent)

    def _check_torrent(self, session, torrent):
        s = torrent.status()
        if s.time_since_download > self._inactive_torrent_timeout and s.time_since_upload > self._inactive_torrent_timeout:
            self._log.info('Removing inactive torrent: %s (%s)' % (torrent.name(), torrent.info_hash()))
            session.remove_torrent(torrent)

